﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Net.Sockets;

namespace Qplus.Infrastructure
{
    public class TCPConnection
    {

        /**
	     * 读取数据的buffer大小
	     */
	    public const int BUFFER_SIZE = 65535;

	    /**
	     * Default value for the maximum time that the tcp connection can remain
	     * active after been halted (in milliseconds)
	     */
	    public const int DEFAULT_SOCKET_TIMEOUT = 2000; // 2sec

	    /** The TCP socket */
	    TcpSocket socket;

	    /**
	     * Maximum time that the connection can remain active after been halted (in
	     * milliseconds)
	     */
	    int socket_timeout;

	    /**
	     * Maximum time that the connection remains active without receiving data
	     * (in milliseconds)
	     */
	    long alive_time;

	    /** The InputStream */
	   // InputStream istream;

	    /** The OutputStream */
	   // OutputStream ostream;

	    /** InputStream/OutputStream error */
	    Exception error;

	    /** Whether it has been halted */
	    Boolean stop;

	    /** Whether it is running */
	    Boolean is_running;

	    /** TcpConnection listener */
	    TCPConnectionListener listener;
	
	    TcpTransport conn;

        /** Costructs a new TcpConnection */
        public TCPConnection(TcpTransport conn, TcpSocket socket, TCPConnectionListener listener)
        {
            init(conn, socket, 0, listener);
            //start();
           
        }


        /** Inits the TcpConnection */
        private void init(TcpTransport conn, TcpSocket socket, long alive_time,
                TCPConnectionListener listener)
        {
            this.conn = conn;
            this.listener = listener;
            this.socket = socket;
            this.socket_timeout = DEFAULT_SOCKET_TIMEOUT;
            this.alive_time = alive_time;
            //		conn.stop = false;
            this.is_running = true;

          //  this.istream = null;
          //  this.ostream = null;
            this.error = null;

            Socket mysocket = this.socket.tcpSocketConnection;
            try
            {
            //    istream = new BufferedInputStream(socket.getInputStream());
           //     ostream = new BufferedOutputStream(socket.getOutputStream());
            }
            catch (Exception e)
            {
                error = e;
                //show 
            }

            if (this.listener != null && error == null)
            {
                this.listener.onConnected(this);
            }
            else
            {
                this.listener.onConnectionTerminated(this, error);
            }
        }
    }
}
